//
//  QFOauthViewController.swift
//  sinaWeibo
//
//  Created by apple on 16/2/28.
//  Copyright © 2016年 Qifeng Yan. All rights reserved.
//

import UIKit
import SVProgressHUD

class QFOauthViewController: UIViewController {

    override func loadView() {
        self.view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let oauthURL = QFNetworkTool.sharedInstance.oauthLoginURL()
        
//        print("oauthURL:\(oauthURL)")

        webView.loadRequest(NSURLRequest(URL: oauthURL))
        
        // 设置导航栏
        setupNavigationBar()
        
    }
    
    /// 设置导航栏
    func setupNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
    // MARK: - 监听按钮的点击
    func autoFill() {
        // 执行js代码,自动填充账号密码
        let js = "document.getElementById('userId').value='3313841688@qq.com';document.getElementById('passwd').value='123456789!'"
//        let js = "document.getElementById('userId').value='378789308@qq.com';document.getElementById('passwd').value='520886'"
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true , completion: nil)
    }
    
    
    // MARK: - 懒加载webView
    lazy var webView = UIWebView()

}


extension QFOauthViewController: UIWebViewDelegate {
    
    // MARK: - UIWebViewDelegate 代理方法
    /// webView 开始加载数据
    func webViewDidStartLoad(webView: UIWebView) {
        // 使用第三方框架提示用户正在加载
        SVProgressHUD.showWithStatus("正在加载数据", maskType: SVProgressHUDMaskType.Black)
    }
    
    /// webView 加载数据完成
    func webViewDidFinishLoad(webView: UIWebView) {
        // 加载完成后将遮盖移除
        SVProgressHUD.dismiss()
    }
    
    /// webView加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss() // 失败也要把这个提示关掉
        if error?.code != 102 {
            // 加载失败
            SVProgressHUD.showErrorWithStatus("加载失败", maskType: SVProgressHUDMaskType.Black)
            
        }
    }
    
    /// webView询问我们是否去加载一个请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        // 获取 返回结果
        let urlString = request.URL?.absoluteString
        
//        print("request:\(urlString)")
        
        // 点击取消按钮 返回的是："http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330"
        // 点授权返回："http://www.baidu.com/?code=d11507fba037c5a6ba206295bab10b3f"
        //  比较发现可以通过判断 ? 后面是不是 code= 就可以判断用户是否授权
        // 判断是不是以 http://www.baidu.com/ redirect_uri 开头
        if urlString!.hasPrefix(QFNetworkTool.sharedInstance.redirect_uri){
            // 截取 ？后面的请求参数
            let query = request.URL?.query
//            print("query:\(query)")
            
            // 判断 query 是不是以 "code=" 开头
            let codeString = "code="
            if query!.hasPrefix(codeString) {
                
                // 截取 code 的值
                let queryNS = query! as NSString // 截取字符串需要转换为oc的字符串
                let code = queryNS.substringFromIndex(codeString.characters.count)

                // 通过 ViewModel 类 发送请求获取 Accesstoken
                QFUserAccountViewModel.sharedInstance.loadAccessToken(code, loadAccessTokenCallBack: { (error) -> () in
                    
                    if error != nil {
                        print("获取accessToken出错了：\(error)")// 提示用户获取失败 打印错误信息
                        SVProgressHUD.showErrorWithStatus("网络不给力")

                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                            
                            self.close()
                        })
                    }
                
                    return
                })
                
                close()
               
//                let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
//                appDelegate.switchRootViewController(false)
                AppDelegate.outSwitchRootViewController(false)
                
                
            } else {
                close()
                
            }
            
            return false
        } else {
            // 如果不是授权回调地址直接加载
            return true
        }
        
    }
}
